"""
RedFire Monitoring Service - Refactored
"""
import sys
from pathlib import Path
import logging.config

# ----------------- PATH SETUP -----------------
try:
    current_file = Path(__file__).resolve()
    project_root = current_file.parents[4]
    if str(project_root) not in sys.path:
        sys.path.insert(0, str(project_root))
except IndexError:
    project_root = Path.cwd()
    if "shared" not in [p.name for p in project_root.iterdir()]:
        while "shared" not in [p.name for p in project_root.iterdir()] and project_root != project_root.parent:
            project_root = project_root.parent
    if str(project_root) not in sys.path:
         sys.path.insert(0, str(project_root))

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
from redis.asyncio import Redis

from redfire_framework import RedFireContainer, RedFireSettings
from redfire_framework.core.database import DatabaseManager as UnifiedDatabaseManager
from redfire_framework.cache.backends import RedisCache as RedisManager
from redfire_framework.logging.manager import configure_logging as get_log_config

from .services.monitoring_service import MonitoringService
from .api import monitoring_routes
from .core import exceptions

# ----------------- GLOBAL SINGLETONS -----------------
db_manager: UnifiedDatabaseManager = None
redis_manager: RedisManager = None
monitoring_service: MonitoringService = None
service_config = ConfigManager().get_service_config("monitoring-service")

# ----------------- DEPENDENCY INJECTION PROVIDERS -----------------
async def get_db_session() -> AsyncSession:
    """Provides a database session for a single request."""
    if not db_manager:
        raise RuntimeError("DatabaseManager not initialized.")
    async with db_manager.get_session() as session:
        yield session

async def get_redis_client() -> Redis:
    """Provides a Redis client for a single request."""
    if not redis_manager:
        raise RuntimeError("RedisManager not initialized.")
    return redis_manager.get_client()

def get_monitoring_service() -> MonitoringService:
    """Provides the singleton instance of the MonitoringService."""
    if not monitoring_service:
        raise RuntimeError("MonitoringService not initialized.")
    return monitoring_service

# ----------------- SERVICE LIFECYCLE -----------------
class MonitoringServiceApp(ServiceBase):
    """Encapsulates the Monitoring Service FastAPI application."""

    def __init__(self):
        super().__init__(service_name="monitoring-service", config=service_config)

    async def on_startup(self):
        """Initializes all necessary resources and managers on service startup."""
        global db_manager, redis_manager, monitoring_service
        
        self.logger.info("Monitoring Service starting up...")
        
        # 1. Initialize Database Manager using centralized database configuration system
        try:
            from shared.data.db_config import load_all_databases, register_all_databases
            
            # Load standardized database configuration
            db_config = load_all_databases("monitoring-service", service_config)
            self.logger.info(f"✅ Loaded {len(db_config.databases)} database configuration(s)")
            
            # Register all databases to the manager
            db_manager = await register_all_databases("monitoring-service", db_config)
            self.logger.info("✅ Database connection established via centralized config system")
        except Exception as e:
            self.logger.error(f"❌ New database config system failed: {e}")
            raise

        # 2. Initialize Redis Manager
        redis_config = service_config.get('redis', {})
        redis_manager = RedisManager(config=redis_config)
        await redis_manager.initialize()
        self.logger.info("RedisManager initialized successfully.")

        # 3. Initialize the Monitoring Service
        monitoring_service = MonitoringService(
            db_manager=db_manager,
            redis_manager=redis_manager,
            config=service_config.get('monitoring', {})
        )
        self.logger.info("MonitoringService singleton created.")

        await super().on_startup()

    async def on_shutdown(self):
        """Cleans up resources on service shutdown."""
        self.logger.info("Monitoring Service shutting down...")
        if db_manager:
            await db_manager.close()
            self.logger.info("Database connections closed.")
        if redis_manager:
            await redis_manager.close()
            self.logger.info("Redis connections closed.")
        await super().on_shutdown()

    def create_app(self) -> FastAPI:
        """Creates and-configures the FastAPI application instance."""
        log_config = get_log_config(self.service_name, self.config.get('logging', {}))
        logging.config.dictConfig(log_config)

        app = super().create_app()
        
        # Include API routes
        app.include_router(monitoring_routes.router, prefix="/api/v1")
        self.logger.info("Monitoring API routes registered under /api/v1/monitoring.")
        
        return app

# ----------------- APPLICATION FACTORY -----------------
def create_service() -> ServiceBase:
    """Factory function to create the service instance."""
    return MonitoringServiceApp()

# Entry point for running the service directly
if __name__ == "__main__":
    service_app = create_service()
    service_app.run()